import React, { useEffect, useState } from "react";
import "./App.css";
import { Upload, Button, message, Row, Col } from "antd";
import { RcFile } from "antd/es/upload/interface";
import axios from "axios";
interface ObjectType {
  name: string;
  url: string;
}

function App() {
  const [objects, setObjects] = useState<ObjectType[]>([]);
  const beforeUpload = (file: RcFile, fileList: RcFile[]) => {
    const { type, name, size } = file;
    // 验证是不是图片
    if (!type.includes("image")) {
      message.error("只可以上传图片");
      return Upload.LIST_IGNORE;
    }
    // 图片大小限制
    if (size > 2 * 1024 * 1024) {
      message.error("图片大小不可以超过2MB");
      return Upload.LIST_IGNORE;
    }

    return true;
  };
  const fetchData = async () => {
    const resp = await axios.get("/api/upload/list");
    setObjects(resp.data.data.objects);
  };
  const handleDelete = async (name: string) => {
    const resp = await axios.delete("/api/upload/delete", { params: { name } });
    fetchData();
  };
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className="App">
      <Upload beforeUpload={beforeUpload} action="/api/upload">
        <Button type="primary">上传文件</Button>
      </Upload>
      <Row>
        {objects.map((v, i) => {
          return (
            <Col span={6} key={i} style={{ padding: 10 }}>
              <img
                src={v.url}
                alt=""
                width="100%"
                height={300}
                style={{ objectFit: "cover" }}
              />
              <span
                style={{
                  position: "absolute",
                  right: 0,
                  top: 0,
                  cursor: "pointer",
                }}
                onClick={() => handleDelete(v.name)}
              >
                X
              </span>
            </Col>
          );
        })}
      </Row>
    </div>
  );
}

export default App;
